package com.tzh.Advice;

import com.tzh.config.i18n.GlobalMsgKey;
import com.tzh.config.i18n.MessageLoading;
import com.tzh.utils.ResultDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类的描述:全局异常处理
 * 创建时间:2019年3月15日
 * 创建人:zoujh
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private MessageLoading messageLoading;

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultDto<?> validErrorExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException exception) throws UnsupportedEncodingException {
        ResultDto<?> result = ResultDto.setFail(messageLoading.getMsg(GlobalMsgKey.GLOBAL_ERROR_MSG, null));
        List<String> dataList = new ArrayList<String>();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            String message = new String(error.getDefaultMessage().getBytes("ISO8859-1"), "UTF-8");
            if (message.startsWith("{") && message.endsWith("}")) {
                message = messageLoading.getMsg(message.replace("{", "").replace("}", ""), null);
            }
            dataList.add(message);
        }
        if (dataList.size() > 0) {
            result.setMsg(dataList.get(0));
        }
        return result;
    }


    @ExceptionHandler({BindException.class})
    public ResultDto<?> validBindExceptionHandler(HttpServletRequest request, BindException exception) throws UnsupportedEncodingException {
        ResultDto<?> result = ResultDto.setFail(messageLoading.getMsg(GlobalMsgKey.GLOBAL_ERROR_MSG, null));
        List<String> dataList = new ArrayList<String>();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            String message = new String(error.getDefaultMessage().getBytes("ISO8859-1"), "UTF-8");
            dataList.add(message);
        }
        if (dataList.size() > 0) {
            result.setMsg(dataList.get(0));
        }
        return result;
    }

//	@ExceptionHandler(ServiceException.class)
//	public ResultDto<?> validServiceExceptionHandler(HttpServletRequest request, ServiceException exception) {
//		ResponseResult result =new ResponseResult();
//        result.setCode(OperationResult.OPERATION_FAIL);
//        result.setMsg(exception.getMessage());
//        return result;
//	}

    @ExceptionHandler(Throwable.class)
    public ResultDto<?> exceptionHandler(HttpServletRequest request, Throwable exception) throws Exception {
        ResultDto<?> result = ResultDto.setFail(messageLoading.getMsg(GlobalMsgKey.GLOBAL_ERROR_MSG, null));
        logger.error("GlobalExceptionHandler:" + exception.getMessage());
        return result;
    }
}
